package com.telesound.dataimport;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class FileUploader extends Thread {
	private String uuid;
	private String filePath;
	private long fileSize;
	private InputStream is;
	private OutputStream os;
	private boolean runFlag=true;
	public static Map<String,Double> processMap=new HashMap<String,Double>();
	public static Map<String,FileUploader> uploaderMap=new HashMap<String,FileUploader>();
	
	public FileUploader(String uuid,String filePath,long fileSize,InputStream is){
		this.uuid=uuid;
		this.filePath=filePath;
		this.fileSize=fileSize;
		this.is=is;
		this.filePath=filePath;
		try {
			os=new FileOutputStream(filePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		//clearUploaderMap();
		uploaderMap.put(uuid, this);
		double process=0;
		long nowSize=0;
		if("".equals(filePath.trim())){
			return;
		}
		try {
			byte[] b=new byte[10240];
			int k=0;
			while(true){
				while(!runFlag){
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				k=is.read(b);
				if(k==-1){
					break;
				}
				os.write(b, 0, k);
				nowSize=nowSize+k;
				process=(double)nowSize/fileSize*100;
				DecimalFormat df  = new DecimalFormat("###.00");   
				String p=df.format(process);
				process=Double.parseDouble(p);
				processMap.put(uuid, process);
			}
			os.close();
			is.close();
			uploaderMap.remove(uuid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static void clearUploaderMap(){
		Set<String> keySet=uploaderMap.keySet();
		Iterator<String> it=keySet.iterator();
		while(it.hasNext()){
			String uuid=it.next();
			FileUploader uploader=uploaderMap.get(uuid);
			if(!uploader.isAlive()){
				uploaderMap.remove(uuid);
				try {
					uploader.os.close();
					uploader.is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static double getProcess(String uuid){
		Double p=processMap.get(uuid);
		if(p==null){
			return 0;
		}
		return p;
	}
	
	public static void suspend(String uuid){
		FileUploader uploader=uploaderMap.get(uuid);
		if(uploader!=null){
			uploader.runFlag=false;
		}
	}
	
	public static void stop(String uuid){
		FileUploader uploader=uploaderMap.get(uuid);
		uploader.interrupt();
		if(uploader!=null){
			try {
				uploader.os.close();
				uploader.is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		uploaderMap.remove(uuid);
	}
	
	public static void resume(String uuid){
		FileUploader uploader=uploaderMap.get(uuid);
		if(uploader!=null){
			uploader.runFlag=true;
		}
	}
	
}
